package com.maozw.api.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.ROUTE_TYPE;

/**
 * @author MAOZW
 * @Description: ${todo}
 * @date 2018/8/10 14:54
 */
@Configuration
public class HttpRequestFilter extends ZuulFilter{

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpRequestFilter.class);

    @Autowired
    private RedisTemplate redisTemplate;

    private static List<String> servicesNames;
    private static List<String> filterUrls;

    static {
        //允许通过的url
        filterUrls = new ArrayList<>();
        filterUrls.add("/1");
        filterUrls.add("/2");
        filterUrls.add("/3");

        //过滤的服务
        servicesNames = new ArrayList<>();
        servicesNames.add("provider-user");
        LOGGER.info("初始化过滤测试数据！");
    }

    /**
     * 过滤器类型
     * pre 事前
     * routing 路由请求时候调用
     * error 发生错误时候调用
     * @return
     */
    @Override
    public String filterType() {
        return ROUTE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否过滤
     * false 不过滤
     * true 过滤
     * @return
     */
    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        //过滤后台服务
        String serviceName = (String) ctx.get("serviceId");

        return servicesNames.contains(serviceName);
    }

    @Override
    public Object run() {

        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest req = ctx.getRequest();
        LOGGER.info("验证开始");
        LOGGER.info(String.format("%s request to %s", req.getMethod(), req.getRequestURL().toString()));

        //放行url
        String url = (String) ctx.get("requestURI");
        if(filterUrls.contains(url)) {
            return null;
        }

        /**
         * 检验逻辑
         */
        LOGGER.info("验证成功");
        return null;
    }
}
